﻿using AutoMapper;
using DTcms.Core.Common.Emum;
using DTcms.Core.Common.Helper;
using DTcms.Core.DBFactory.Database;
using DTcms.Core.IServices;
using DTcms.Core.Model.Models;
using DTcms.Core.Model.ViewModels;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace DTcms.Core.Services
{
    /// <summary>
    /// 文章投稿接口实现
    /// </summary>
    public class ArticleContributeService : BaseService, IArticleContributeService
    {

        private readonly IMapper _mapper;
        private readonly IUserService _userService;


        public ArticleContributeService(
            IDbContextFactory contentFactory,
            IUserService userService,
            IMapper mapper) : base(contentFactory)
        {
            _userService = userService;
            _mapper = mapper;
        }

        /// <summary>
        /// 修改一条记录
        /// </summary>
        public async Task<bool> UpdateAsync(long id, ArticleContributeEditDto modelDto, WriteRoRead writeAndRead = WriteRoRead.Write)
        {
            _context = _contextFactory.CreateContext(writeAndRead);//连接数据库

            SiteChannel siteChannel = await _context.Set<SiteChannel>().FirstOrDefaultAsync(x => x.Id == modelDto.ChannelId);
            //检查频道是否存在
            if (siteChannel == null)
            {
                throw new ResponseException($"频道{modelDto.ChannelId}不存在或已删除", ErrorCode.NotFound);
            }
            //检查是否可以投稿
            if (siteChannel.IsContribute == 0)
            {
                throw new ResponseException($"该频道不允许投稿", ErrorCode.NotFound);
            }
            modelDto.SiteId = siteChannel.SiteId;
            //检查站点是否存在
            if (await _context.Set<Sites>().FirstOrDefaultAsync(x => x.Id == siteChannel.SiteId) == null)
            {
                throw new ResponseException($"站点{modelDto.SiteId}不存在或已删除", ErrorCode.NotFound);
            }
            //查找记录
            //注意：要使用写的数据库进行查询，才能正确写入数据主库
            var model = await _context.Set<ArticleContribute>().FirstOrDefaultAsync(x => x.Id == id);
            if (model == null)
            {
                throw new ResponseException($"数据{id}不存在或已删除", ErrorCode.NotFound);
            }
            //获取当前用户名
            modelDto.UpdateBy = await _userService.GetUserNameAsync();
            modelDto.UpdateTime = DateTime.Now;
            //更新操作AutoMapper替我们完成，只需要调用保存即可
            _mapper.Map(modelDto, model);
            //通过
            if (modelDto.Status == 1)
            {
                #region 审核通过添加文章到对应的频道
                //类别关系
                List<ArticleCategoryRelationDto> categoryRelations = new List<ArticleCategoryRelationDto>();
                for (int i = 0; i < modelDto.Categorys.Length; i++)
                {
                    categoryRelations.Add(new ArticleCategoryRelationDto()
                    {
                        CategoryId = Convert.ToInt64(modelDto.Categorys[i]),
                        ArticleId = 0
                    });
                }
                ArticlesAddDto articlesDto = new ArticlesAddDto();
                articlesDto.Title = model.Title;
                articlesDto.Status = 0;
                articlesDto.Source = model.Source;
                articlesDto.Author = model.Author;
                articlesDto.ChannelId = model.ChannelId;
                articlesDto.SiteId = model.SiteId;
                articlesDto.Content = model.Content;
                articlesDto.Zhaiyao = HtmlHelper.CutString(model.Content, 250);
                articlesDto.AddBy = model.UserName;
                articlesDto.AddTime = model.AddTime;
                articlesDto.ImgUrl = model.ImgUrl;
                //所属分类
                articlesDto.ArticleCategoryRelations = categoryRelations;
                //扩展字段
                List<ArticleFieldValueAddDto> fieldValueAdds = new List<ArticleFieldValueAddDto>();
                foreach (var field in modelDto.Fields)
                {
                    fieldValueAdds.Add(new ArticleFieldValueAddDto()
                    {
                        FieldId = field.FieldId,
                        FieldName = field.FieldName,
                        FieldValue = field.FieldValue
                    });
                }
                articlesDto.ArticleFields = fieldValueAdds;
                //相册
                if (siteChannel.IsAlbum==1)
                {
                   var albums= JsonHelper.ToJson<List<ArticleAlbumDto>>(model.AlbumMeta);
                    articlesDto.ArticleAlbums = albums;
                }
                //附件
                if (siteChannel.IsAttach == 1)
                {
                    var attachs = JsonHelper.ToJson<List<ArticleAttachDto>>(model.AttachMeta);
                    articlesDto.ArticleAttachs = attachs;
                }
                Articles articlesModel = new Articles();
                _mapper.Map(articlesDto, articlesModel);
                articlesModel.AddTime = model.AddTime;
                await _context.Set<Articles>().AddAsync(articlesModel); 
                #endregion
            }
            //提交保存
            return (await _context.SaveChangesAsync() >= 0);
            //else
            //{
            //    //提交保存
            //    return await this.SaveAsync();
            //}
        }


        /// <summary>
        /// 修改一条记录
        /// </summary>
        public async Task<bool> UserUpdateAsync(long id, ArticleContributeEditDto modelDto, WriteRoRead writeAndRead = WriteRoRead.Write)
        {
            _context = _contextFactory.CreateContext(writeAndRead);//连接数据库

            SiteChannel siteChannel = await _context.Set<SiteChannel>().FirstOrDefaultAsync(x => x.Id == modelDto.ChannelId);
            //检查频道是否存在
            if (siteChannel == null)
            {
                throw new ResponseException($"频道{modelDto.ChannelId}不存在或已删除", ErrorCode.NotFound);
            }
            //检查是否可以投稿
            if (siteChannel.IsContribute == 0)
            {
                throw new ResponseException($"该频道不允许投稿", ErrorCode.NotFound);
            }
            modelDto.SiteId = siteChannel.SiteId;
            //检查站点是否存在
            if (await _context.Set<Sites>().FirstOrDefaultAsync(x => x.Id == siteChannel.SiteId) == null)
            {
                throw new ResponseException($"站点{modelDto.SiteId}不存在或已删除", ErrorCode.NotFound);
            }
            //查找记录
            //注意：要使用写的数据库进行查询，才能正确写入数据主库
            var model = await _context.Set<ArticleContribute>().FirstOrDefaultAsync(x => x.Id == id);
            if (model == null)
            {
                throw new ResponseException($"数据{id}不存在或已删除", ErrorCode.NotFound);
            }
            var user = await _userService.GetUserAsync();
            if (model.UserName!=user.UserName)
            {
                throw new ResponseException($"请勿修改别人的数据", ErrorCode.NotFound);
            }
            //获取当前用户名
            modelDto.UpdateBy = user.UserName;
            modelDto.UpdateTime = DateTime.Now;
            //更新操作AutoMapper替我们完成，只需要调用保存即可
            _mapper.Map(modelDto, model);
            //通过
            if (modelDto.Status == 1)
            {
                #region 审核通过添加文章到对应的频道
                //类别关系
                List<ArticleCategoryRelationDto> categoryRelations = new List<ArticleCategoryRelationDto>();
                for (int i = 0; i < modelDto.Categorys.Length; i++)
                {
                    categoryRelations.Add(new ArticleCategoryRelationDto()
                    {
                        CategoryId = Convert.ToInt64(modelDto.Categorys[i]),
                        ArticleId = 0
                    });
                }
                ArticlesAddDto articlesDto = new ArticlesAddDto();
                articlesDto.Title = model.Title;
                articlesDto.Status = 0;
                articlesDto.Source = model.Source;
                articlesDto.Author = model.Author;
                articlesDto.ChannelId = model.ChannelId;
                articlesDto.SiteId = model.SiteId;
                articlesDto.Content = model.Content;
                articlesDto.Zhaiyao = HtmlHelper.CutString(model.Content, 250);
                articlesDto.AddBy = model.UserName;
                articlesDto.AddTime = model.AddTime;
                articlesDto.ImgUrl = model.ImgUrl;
                //所属分类
                articlesDto.ArticleCategoryRelations = categoryRelations;
                //扩展字段
                List<ArticleFieldValueAddDto> fieldValueAdds = new List<ArticleFieldValueAddDto>();
                foreach (var field in modelDto.Fields)
                {
                    fieldValueAdds.Add(new ArticleFieldValueAddDto()
                    {
                        FieldId = field.FieldId,
                        FieldName = field.FieldName,
                        FieldValue = field.FieldValue
                    });
                }
                articlesDto.ArticleFields = fieldValueAdds;
                Articles articlesModel = new Articles();
                _mapper.Map(articlesDto, articlesModel);
                await _context.Set<Articles>().AddAsync(articlesModel);
                #endregion
            }
            //提交保存
            return (await _context.SaveChangesAsync() >= 0);
            //else
            //{
            //    //提交保存
            //    return await this.SaveAsync();
            //}
        }

        /// <summary>
        /// 获取稿件总数量
        /// </summary>
        public async Task<int> QueryCountAsync(Expression<Func<ArticleContribute, bool>> funcWhere, WriteRoRead writeAndRead = WriteRoRead.Read)
        {
            _context = _contextFactory.CreateContext(writeAndRead);//连接数据库
            return await _context.Set<ArticleContribute>().Where(funcWhere).CountAsync();
        }

    }
}
